package com.hancheng.commoncloud.framework.aop;


import com.alibaba.fastjson.JSON;
import com.hancheng.commoncloud.framework.annotation.Log;
import com.hancheng.commoncloud.framework.util.LocalUserInfoUtil;
import com.hancheng.commoncloud.framework.util.WebUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 请求拦截
 */
@Aspect
@Component
public class MvcAspect {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void advice() {

    }

    /**
     * 每次请求时在路径前后记录下请求URL和请求结果
     *
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("advice()")
    public Object doPage(ProceedingJoinPoint point) throws Throwable {
        Logger logger = LoggerFactory.getLogger(point.getTarget().getClass());
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        try {
            if (Objects.isNull(method.getAnnotation(Log.class))) {
                return point.proceed();
            }
            String url = WebUtils.getRequest().getRequestURI();
            long start = System.currentTimeMillis();
            logger.info("请求url: {}, 参数:{}", url, point.getArgs());
            Object obj = point.proceed();
            logger.info("响应参数: {},耗时: {}", JSON.toJSONString(obj), System.currentTimeMillis() - start);
            return obj;
        } catch (Exception t) {
            logger.error("错误信息: ", t);
            throw t;
        } finally {
            LocalUserInfoUtil.remove();
        }
    }
}
